﻿

namespace LS.Nc6.Web.Entry.Areas.Systems.Controllers
{
    /// <summary>
    ///菜单管理
    /// </summary>
    [Route("[area]/[controller]/[action]")]
    [Area("Systems")]
    [ApiDescriptionSettings("Default")]
    public class MenuController : BaseAdminController
    {
        #region MenuController
       
        private readonly ISysFunctionService _functionService;
        private readonly ISysMenuService _menuService;
        private readonly ICache _cache;
        public MenuController(ISysFunctionService functionService, ISysMenuService menuService, IOptions<CacheOptions> cacheOptions, Func<string, ISingleton, object> resolveNamed)
            : base(cacheOptions, resolveNamed)
        {
            _functionService = functionService;
            _menuService = menuService;
            _cache = resolveNamed(cacheOptions.Value.CacheType.ToString(), default) as ICache;
        }

        #endregion
       
        public async Task<ActionResult> Index()
        {
            SysPower(SysMenuConstant.MENU_MANAGE, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());
            ViewBag.FunList = JsonSerializer.Serialize( await _functionService.List(a=> true,(a)=>new { a.Id}),CommonMethodHelper.MyJsonOptions);
            return View();
        }

       
        public ActionResult GenerateCode()
        {
            return View();
        }
        public  ActionResult MsSql()
        {
            return View();
        }
       

        #region 页面
        /// <summary>
        /// 创建操作功能
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateFunction()
        {
            SysPower(SysMenuConstant.MENU_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString());
            return View("EditFunction");
        }
        /// <summary>
        ///创建菜单
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> CreateMenu()
        {
            SysPower(SysMenuConstant.MENU_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString());
            var model = new SysMenuEntity();
            ViewBag.FunList = await _functionService.List(a=>true, (a) => new { a.Id });
            model.Isvisible = true;
            model.Isenable = true;
            #region 增加是自动获取菜单代码和序列号
            string strwhere = string.Empty;
            int pid = Request.Query["pid"].ToString().GetQueryValueOrNull<int>(0);
            int menseq = await _menuService.GetMaxPartMenu(pid);
          
            model.MenuSeq = menseq+1;
            model.ParentId = pid;
            model.TargetType = 0;
            #endregion
           
            return View("EditMenu", model);
        }
        /// <summary>
        ///编辑菜单
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> EditMenu(long id)
        {
            SysPower(SysMenuConstant.MENU_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString());
            var model = await _menuService.GetByIdAsync(id);
            if (model == null)
            {    
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            ViewBag.FunList = await _functionService.List(a=>true, (a) => new { a.Id });
            var expable = Expressionable.Create<SysMenuFunctionEntity>();
            expable.And(it=>it.MenuCode == model.MenuCode);
            var exp= expable.ToExpression();
            ViewBag.MenuFunList = await _menuService.GetMenuFunction(exp);
            return View(model);
        }
        /// <summary>
        /// 设置父级菜单项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> EditMenuParent(long id)
        {
            ViewBag.Id = id;
            var model= await _menuService.GetByIdAsync(id);
            if (model!=null)
            {
                ViewBag.Name = model.MenuName;
                ViewBag.CurParentId= model.ParentId;
                
            }
            return View();
        }
        #endregion

        #region  公共方法
        /// <summary>
        /// 保存功能
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async  Task<ResponseResult> SaveFunction([FromBody]SysFunctionEntity model)
        {
            if( await _functionService.ExistsFunCode(model.Id.ToString(), model.FunCode))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_BMYCZ); 
            }
            long result=await _functionService.InsertAsync(model);
            return ResponseHelper.SaveResult(result);
        }

        /// <summary>
        /// 保存菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async  Task<ResponseResult> Save([FromBody]SysMenuEntity model)
        {
            bool power = true;
            if (model.ParentId>0)
            {
                var  pmodel= await _menuService.GetByIdAsync(model.ParentId.Value);
                model.Menulevel = pmodel.Menulevel + 1;   
            }
            else
            {
                model.Menulevel = 0;
            }
            List<SysMenuFunctionEntity> list = new List<SysMenuFunctionEntity>();
            //处理fun 功能
            if (model.Funcode != null )
            {
                var funcode = CommonUtil.GetStringArrayNoNull(model.Funcode);
                foreach (var item in funcode)
                {
                    list.Add(new SysMenuFunctionEntity
                    {
                        FunCode = item,
                        MenuCode = model.MenuCode
                    });
                }
            }
            int result = 0;
            if (model.Id>0)
            {
                power = SysPower(SysMenuConstant.MENU_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var editmodel =await _menuService.GetByIdAsync(model.Id);
                if (editmodel == null || editmodel.IsDeleted == 1)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.OPERATE_SJYSC);
                }
                CommonMethodHelper.MapperToModel(editmodel, model, null);
                
                result =await _menuService.UpdateMenuFun(editmodel, list);
            }
            else
            {
                power = SysPower(SysMenuConstant.MENU_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                if (await _menuService.ExistsMenuCode(model.MenuCode))
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_BMYCZ);
                }
                result = await _menuService.InsertMenuFun(model, list);
            }
            if (result > 0)
            {
                await  _cache.DelByPatternAsync("CurentMenu_" + UserInfo.ID.ToString());
                await  _cache.DelByPatternAsync("CurentPower_" + UserInfo.ID.ToString());
            }
            return  ResponseHelper.SaveResult(result);
            
        }

        /// <summary>
        /// 获取所有菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
       public async Task<ResponseResultDataList> GetAllMenu()
        {
            string menuname = RequestHelper.FilterParam(Request.Query["menuname"]);

            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = await GetMenuListAllData(menuname), count = 100 };
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Del([FromBody]DeletDataInput input)
        {
            var r = SysPower(SysMenuConstant.MENU_DICTIONARY_MANAGE, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_WSCQX);
            }
            if (string.IsNullOrEmpty(input.Ids))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            int result= await _menuService.DeleteAsync(input.Ids.ToString());
            return ResponseHelper.DeleteResult(result);
        }

        /// <summary>
        /// 获取功能
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResultDataList> GetAllFunction()
        {
            var fundata =await _functionService.List(a=>true,a=>a.FunSeq);
            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = fundata, count = 100 };
        }

        /// <summary>
        /// 获取dtree muen 菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<dynamic> GetdtreeData(long id)
        {
            return new
            {
                code = 0,
                msg = "操作成功",
                data = await GetMenuTreeListAllData(id)
            };
           
        }
        #endregion

        #region 私用方法


        private void GetChildrenMenu(Hashtable etm, IList<SysMenuEntity> listpartmenu,long pid)
        {
            var children = listpartmenu.Where(w => w.ParentId == pid);
            List<Hashtable> lsetm = new List<Hashtable>();
            if (children != null && children.Count() > 0)
            {
                foreach (var item in children)
                {
                    Hashtable etmchildren = new Hashtable();
                    etmchildren.Add("id", item.Id.ToString());
                    etmchildren.Add("title", item.MenuName);
                    etmchildren.Add("parentId", pid.ToString());
                    GetChildrenMenu(etmchildren, listpartmenu, item.Id);
                    lsetm.Add(etmchildren);
                }
                if (lsetm.Count > 0)
                {
                    etm.Add("children", lsetm);
                }
            }
        }

       

        private async Task<List<Hashtable>> GetMenuListAllData(string menuName)
        {
            List<Hashtable> lsetm = new List<Hashtable>();
           
            var expable = Expressionable.Create<SysMenuEntity>();
            expable.AndIF(!string.IsNullOrEmpty(menuName), a => a.MenuName.Contains(menuName));
            var exp = expable.ToExpression();
            var  menulist = await _menuService.MenuList(exp);
            foreach (var item in menulist)
            {
                Hashtable etm = new Hashtable();
                etm.Add("id", item.Id);
                etm.Add("name", item.MenuName);
                etm.Add("url", item.MenuUrl);
                etm.Add("menuSeq", item.MenuSeq);
                etm.Add("iconCls", item.MenuIcon);
                etm.Add("menuCode", item.MenuCode);
                etm.Add("pId", item.ParentId);
                etm.Add("open", true);
                etm.Add("description", item.Remark);
                etm.Add("funcode", item.Funcode);
                lsetm.Add(etm);
            }
            return lsetm;
        }


        private async Task<List<Hashtable>> GetMenuTreeListAllData(long id)
        {
            List<Hashtable> lsetm = new List<Hashtable>();
           
            var expable = Expressionable.Create<SysMenuEntity>();
            expable.And(a=>a.Isenable ==true && a.Id!= id);
            var exp = expable.ToExpression();
            var menulist = await _menuService.List(exp,(a)=>new { a.Id});
            foreach (var item in menulist)
            {
                Hashtable etm = new Hashtable();
                etm.Add("id", item.Id.ToString());
                etm.Add("title", item.MenuName);
                etm.Add("parentId", item.ParentId.ToString());
              
                lsetm.Add(etm);
            }
            return lsetm;
        }
        #endregion
    }
}